<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        h1 {
            text-align: center;
        }
    </style>
</head>

<body>

    <h1>0</h1>
    <button id="btn1">点击开始</button>

    <button id="btn2">清除计时器</button>

    <script>
        var timer1, num = 0;
        var h1 = document.querySelector("h1");
        btn1.onclick = function() {
            interval(function(){
                num++;
                h1.innerHTML = num;
            }, 300);
        }

        function interval(callback, duration) {
            timer1 = setTimeout(function(){
                callback();
                interval(callback, duration);
            }, duration);
        }

        btn2.onclick = function() {
            clearTimeout(timer1);
        }
    </script>
</body>

</html>
